﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using Se.Framework.Common;
using Se.Framework.Common.Config;
using Se.Framework.Common.Data;
using Se.Framework.Common.Security;

namespace Se.Framework.Web
{
    public class FormsAuthenticationUserDataProvider<TUserData> : IUserDataProvider<TUserData>
        where TUserData : class, IUserData
    {
        public TUserData CurrentUserData
        {
            get
            {
                TUserData user = null;
                if (HttpContext.Current.User != null)
                {
                    user = HttpContext.Current.User.Identity as TUserData;
                }

                if (user == null)
                {
                    HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (authCookie == null)
                    {
                        var key = ObjectRegistry.Current.Resolve<IUserKeyProvider>().GetCurrentUserKey();
                        if (key == null)
                        {
                            throw new Exception("There is no user information available.");
                        }
                        else
                        {
                            LoginUser(Configuration.Current.DebugSid);
                            authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                        }
                    }
                    // Get the authentication ticket and rebuild the principal 
                    // & identity
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    user = ObjectRegistry.Current.Resolve<TUserData>();
                    user.Load(authTicket.Name);
                    HttpContext.Current.User = new UserPrincipal(user, HttpContext.Current.User);
                }

                return user;
            }
        }

        public virtual void LoginUser(object key)
        {
            string sid = key.ToString();
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, sid, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, sid);
            HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
            HttpContext.Current.Response.Cookies.Add(faCookie);
        }

        public virtual void LogoutUser()
        {
        }
    }
}
